package com.lagou.session;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 默认执行器实现类
 *
 * <p>
 * 执行数据库操作
 *
 * @author Tengfei.Wang
 * @date 26/8/2020
 */
@Slf4j
public class SimpleExecutor implements Executor {

    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object params) {
        Connection connection = null;
        try {
            //处理参数，重组SQL
            connection = getConnection(configuration);
            String sql = mapperStatement.getSql();
            //重组sql
            BoundSql boundSql = getBoundSql(sql);
            sql = sql.replaceAll("[\r\n]", "");
            log.info("==>  Preparing: {}", sql.trim());
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

            //如果参数类型是Integer 或者String直接赋值
            setStatementParameter(mapperStatement, boundSql, preparedStatement, params);

            //重组返回对象
            Class<?> resultClass = mapperStatement.getResultType();
            ResultSet resultSet = preparedStatement.executeQuery();
            List<Object> list = new ArrayList<Object>();
            //获取元数据，包含参数的名称
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (resultSet.next()) {
                Object o = resultClass.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    //获取参数name
                    String columnName = metaData.getColumnName(i);
                    //获取参数value
                    Object fieldValue = resultSet.getObject(columnName);
                    //创建属性描述器，为属性生成读写方法
                    PropertyDescriptor descriptor = new PropertyDescriptor(columnName, resultClass);
                    Method writeMethod = descriptor.getWriteMethod();
                    writeMethod.invoke(o, fieldValue);
                }
                list.add(o);
            }
            return (List<E>) list;
        } catch (SQLException thenables) {
            thenables.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            closeSession(connection);
        }
        return null;
    }

    public void update(Configuration configuration, MapperStatement mapperStatement, Object params) {
        Connection connection = null;
        try {
            //处理参数，重组SQL
            connection = getConnection(configuration);
            String sql = mapperStatement.getSql();
            //重组sql
            BoundSql boundSql = getBoundSql(sql);
            sql = sql.replaceAll("[\r\n]", "");
            log.info("==>  Preparing: {}", sql.trim());
            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
            //如果参数类型是Integer 或者String直接赋值
            setStatementParameter(mapperStatement, boundSql, preparedStatement, params);
            preparedStatement.executeUpdate();

        } catch (SQLException thenables) {
            thenables.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } finally {
            closeSession(connection);
        }
    }

    private void setStatementParameter(MapperStatement mapperStatement, BoundSql boundSql, PreparedStatement preparedStatement, Object params) throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class<?> parameterClass = mapperStatement.getParameterType();
        if (parameterClass == null) {
            return;
        }

        Object[] param = (Object[]) params;
        if (isBaseType(parameterClass)) {
            preparedStatement.setObject(1, param[0]);
            return;
        }
        //设置请求参数
        List<ParameterMapping> parameterList = boundSql.getParameterMappingList();
        StringBuffer sb = new StringBuffer();
        sb.append("==> Parameters:  ");
        for (int i = 0; i < parameterList.size(); i++) {
            ParameterMapping parameterMapping = parameterList.get(i);
            String content = parameterMapping.getContent();
            Field field = parameterClass.getDeclaredField(content);
            field.setAccessible(true);
            preparedStatement.setObject(i + 1, field.get(param[0]));
            sb.append(field.get(param[0])).append(", ");
        }
        log.info(sb.substring(0, sb.length() - 2));
    }

    public static boolean isBaseType(Class<?> clazz) {
        if (clazz.equals(java.lang.Integer.class) || clazz.equals(java.lang.Byte.class) ||
                clazz.equals(java.lang.Long.class) || clazz.equals(java.lang.Double.class) ||
                clazz.equals(java.lang.Float.class) || clazz.equals(java.lang.Character.class) ||
                clazz.equals(java.lang.Short.class) || clazz.equals(java.lang.Boolean.class)) {
            return true;
        }
        return false;
    }

    private Connection getConnection(Configuration configuration) throws SQLException {
        DataSource dataSource = configuration.getDataSource();
        return dataSource.getConnection();
    }

    private void closeSession(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 完成sql替换以及解析工作
     */
    private BoundSql getBoundSql(String sql) {
        //表里处理类，配置标记解析器完成对占位符的解析工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();
        return new BoundSql(parse, parameterMappings);

    }
}
